package com.smartlock.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by pan on 12/01/2017.
 */
public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String postWithJson(String url, String jsonValues) {

        HttpClient httpClient = HttpClientBuilder.create().build();

        try {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(jsonValues);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            return parseResponse(response);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    /**
     * // * 向指定url发送get方法的请求 // * // * @param url 发送请求的url // * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * // * @return result 所代表远程资源的响应结果 //
     */
    public static String get(String url, String param) {
        // 返回结果
        String result = "";
        BufferedReader in;
        in = null;
        try {
            // url
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // Map<String, List<String>> map = connection.getHeaderFields();

            // 遍历所有的响应头字段
            /*
             * for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); }
             */
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        // 使用finally块来关闭输入流
        finally {
            close(in);
        }

        // 如果外部接口返回为空，返回其他错误原因
        if (StringUtils.isBlank(result)) {
            result = "{\"result\":\"other error\"}";
        }

        return result;
    }

    /**
     * 将服务器返回的数据包装成为String
     * 
     * @param response
     * @return
     * @throws IOException
     */
    private static String parseResponse(HttpResponse response) throws IOException {

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed:" + response.getStatusLine());
        }

        // Read the response body
        return EntityUtils.toString(response.getEntity());
    }

    /**
     * @param closeable
     */
    private static void close(Closeable... closeable) {
        for (Closeable c : closeable) {
            try {
                if (c != null) {
                    c.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
